# -*- coding: utf-8 -*-
# @Env    : v-3.5.4
# @File   : forms.py
# @Author : Kevin.Liu
# @Date   : 2019/1/5
# @Desc   : 验证模块
import re

from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Length, ValidationError, EqualTo

from blog.models import User


class CommentFrom(FlaskForm):
    """评价Form校验"""
    # 设置Input框的校验器
    name = StringField("Name", validators=[DataRequired(), Length(max=255)])
    text = StringField("Comment", validators=[DataRequired()])


class LoginForm(FlaskForm):
    """登录表单"""
    username = StringField("Username", [DataRequired(), Length(max=255)])
    password = PasswordField("Password", [DataRequired()])

    def validate(self):
        """检查登录账户信息"""
        check_validate = super(LoginForm, self).validate()

        # 如果验证没有通过
        if not check_validate:
            return False

        # 检查用户是否存在
        user = User.query.filter_by(username=self.username.data).first()
        if not user:
            self.username.errors.append("无效的用户名或密码")
            return False

        if not user.check_password(self.password.data):
            self.password.errors.append("用户名或密码错误")
            return False

        return True


class RegisterForm(FlaskForm):
    """注册表单"""
    username = StringField("Username", [DataRequired(), Length(max=255)])
    password = PasswordField("Password", [DataRequired(), Length(min=8)])
    confirm = PasswordField("Confirm Password", [DataRequired(), EqualTo("password")])
    recaptcha = RecaptchaField()

    def validate(self):
        check_validate = super(RegisterForm, self).validate()

        # 验证不通过
        if not check_validate:
            return False

        # 检查用户是否存在
        user = User.query.filter_by(username=self.username.data).first()
        if user:
            self.username.errors.append("用户已存在")
            return False
        return True


class PostForm(FlaskForm):
    """文章表单"""
    title = StringField("Tittle", [DataRequired(), Length(max=255)])
    text = StringField("Blog Content", [DataRequired])


def costom_email(form_object, field_object):
    """定义一个校验器"""
    if not re.match(r"[^@+@[^@]+\.[^@]]+", field_object.data):
        raise ValidationError("字段必须是有效的电子邮件地址.")
